// 获取DOM元素
const apiKeyInput = document.getElementById('api-key');
const apiProviderSelect = document.getElementById('api-provider');
const openaiModelSelect = document.getElementById('openai-model-select');
const deepseekModelSelect = document.getElementById('deepseek-model-select');
const languageSelect = document.getElementById('language-select');
const saveButton = document.getElementById('save-settings');
const successMessage = document.getElementById('success-message');
const togglePasswordButton = document.getElementById('toggle-password');
const apiKeyDescription = document.getElementById('api-key-description'); // 新增

// 根据选择的API提供商显示相应的模型选择并更新API密钥提示
function updateModelSelectVisibility() {
    const selectedProvider = apiProviderSelect.value;
    const openaiModelContainer = openaiModelSelect.closest('.setting-item');
    const deepseekModelContainer = deepseekModelSelect.closest('.setting-item');
    
    if (selectedProvider === 'openai') {
        openaiModelContainer.style.display = 'block';
        deepseekModelContainer.style.display = 'none';
        apiKeyDescription.textContent = '请在此处输入您的OpenAI API密钥，它将被安全地存储在您的浏览器中。';
    } else {
        openaiModelContainer.style.display = 'none';
        deepseekModelContainer.style.display = 'block';
        apiKeyDescription.textContent = '请在此处输入您的DeepSeek API密钥，它将被安全地存储在您的浏览器中。';
    }
}

// 加载已保存的设置
chrome.storage.local.get(['apiKey', 'apiProvider', 'openaiModel', 'deepseekModel', 'language'], (result) => {
    if (result.apiKey) {
        apiKeyInput.value = result.apiKey;
    }
    if (result.apiProvider) {
        apiProviderSelect.value = result.apiProvider;
    } else {
        // 默认选择 OpenAI
        apiProviderSelect.value = 'openai';
    }
    if (result.openaiModel) {
        openaiModelSelect.value = result.openaiModel;
    } else {
        // 默认选择 GPT-3.5-turbo
        openaiModelSelect.value = 'gpt-3.5-turbo';
    }
    if (result.deepseekModel) {
        deepseekModelSelect.value = result.deepseekModel;
    } else {
        // 默认选择 DeepSeek Chat
        deepseekModelSelect.value = 'deepseek-chat';
    }
    if (result.language) {
        languageSelect.value = result.language;
    } else {
        // 默认设置为中文
        languageSelect.value = 'chinese';
    }
    
    // 初始化时更新模型选择的显示状态
    updateModelSelectVisibility();
});

// 监听API提供商变化
apiProviderSelect.addEventListener('change', function() {
    // 更新模型选择的显示状态
    updateModelSelectVisibility();
    
    // 更新API密钥输入框的placeholder
    if (this.value === 'openai') {
        apiKeyInput.placeholder = '请输入OpenAI API密钥...';
    } else if (this.value === 'deepseek') {
        apiKeyInput.placeholder = '请输入DeepSeek API密钥...';
    }
});

// 初始化时设置默认的placeholder
window.addEventListener('DOMContentLoaded', () => {
    // ...其他初始化代码...
    
    // 设置初始placeholder
    const defaultProvider = apiProviderSelect.value || 'openai';
    apiKeyInput.placeholder = defaultProvider === 'openai' 
        ? '请输入OpenAI API密钥...' 
        : '请输入DeepSeek API密钥...';
});

// 切换密钥显示/隐藏
togglePasswordButton.addEventListener('click', () => {
    const type = apiKeyInput.type === 'password' ? 'text' : 'password';
    apiKeyInput.type = type;
    
    // 更新图标状态
    togglePasswordButton.classList.toggle('showing');
    
    // 更新aria-label
    togglePasswordButton.setAttribute('aria-label', 
        type === 'password' ? '显示密钥' : '隐藏密钥'
    );
});

// 验证API密钥格式
function validateApiKey(apiKey, provider) {
    if (!apiKey) {
        return '请输入API密钥';
    }
    
    if (provider === 'openai' && !apiKey.startsWith('sk-')) {
        return 'OpenAI API密钥格式不正确，应以sk-开头';
    }
    
    if (apiKey.length < 32) {
        return 'API密钥长度不足，请检查是否完整';
    }
    
    return null;
}

// 显示错误消息
function showError(message) {
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.textContent = message;
    apiKeyInput.parentNode.appendChild(errorDiv);
    
    setTimeout(() => {
        errorDiv.remove();
    }, 3000);
}

// 保存设置
saveButton.addEventListener('click', () => {
    const apiKey = apiKeyInput.value.trim();
    const apiProvider = apiProviderSelect.value;
    const openaiModel = openaiModelSelect.value;
    const deepseekModel = deepseekModelSelect.value;
    const language = languageSelect.value;
    
    const error = validateApiKey(apiKey, apiProvider);
    if (error) {
        showError(error);
        return;
    }
    
    chrome.storage.local.set({
        apiKey: apiKey,
        apiProvider: apiProvider,
        openaiModel: openaiModel,
        deepseekModel: deepseekModel,
        language: language
    }, () => {
        // 显示成功消息
        successMessage.style.display = 'block';
        setTimeout(() => {
            successMessage.style.display = 'none';
        }, 2000);
    });
});
